<?php

class FormFilter_Select extends FormFilter
{

  public $table;

  public $primaryKey;

  public $foreignKey;

  public $query;

  public $queryData;

  public $queryParams;

  public $options;

  public $keyField;

  public $labelField;

  public $showEmpty = true;

  public $emptyValue = '';

  public $emptyLabel = '';

  public $requiredMessage;

  public $requiredRedirect;

  public function render()
  {
    $view = $this->getView();

    $view->set('options', $this->getOptions());
    $view->set('showEmpty', $this->showEmpty);
    $view->set('emptyValue', $this->emptyValue);
    $view->set('emptyLabel', $this->emptyLabel);

    return parent::render();
  }

  public function getTable()
  {
    if (empty($this->table)) {
      $this->table = $this->form->getTable();
    }

    return $this->table;
  }

  public function getKeyField()
  {
    if (empty($this->keyField)) {
      $this->keyField = $this->getPrimaryKey();
    }

    return $this->keyField;
  }

  public function getLabelField()
  {
    if (empty($this->labelField)) {
      $this->labelField = $this->getPrimaryKey();
    }

    return $this->labelField;
  }

  public function getOptions()
  {
    if (is_null($this->options)) {
      if (empty($this->query)) {
        $this->query = DAO::getInstance()->query()->from($this->getTable())->select($this->getKeyField(), $this->getLabelField());
      }
      elseif (is_string($this->query)) {
        $this->query = DAO::getInstance()->query($this->query);
      }

      $this->query->setParams($this->queryParams);

      $result = $this->query->execute($this->queryData);

      $data = $result->fetchAll();

      $options = sy_array_to_options($data, $this->getKeyField(), $this->getLabelField());

      $options = $this->filters('options', $options, $data);

      $this->options = $options;
    }

    return $this->options;
  }

}

?>